from django.conf.urls.defaults import patterns, url

DEFAULT_BACKEND_PREFIX = 'backend'

class AlreadyRegistered(Exception):
    pass

class NotRegistered(Exception):
    pass

class BackendSite(object):
    """
    Keeps track of the backend sections and actions and builds the URLs to use
    in the djangos urlconf.
    """
    def __init__(self, backend_prefix=DEFAULT_BACKEND_PREFIX):
        self._register = list()
        self.index = None
        self.backend_prefix = backend_prefix
    
    def register(self, section, position=0):
        section.set_backend_prefix(self.backend_prefix)
        self._register.insert(position, section)
    
    def get_context(self):
        sections = list()
        for s in self._register:
            sections.append({
                'name': self.backend_prefix + '.' + s.name,
                'menu_name': s.menu_name,
                'page_title': s.page_title,
            })
        
        return {
            'sections': self._register
        }
    
    def get_urls(self):
        urls = list()
        
        for section in self._register:
            urls += section.get_urls()
        
        return patterns('', *urls)

# This global object represents the default backend site, for the common case.
# You can instantiate BackendSite in your own code to create a custom backend site.
site = BackendSite()

